#!python
# -*- coding: utf-8 -*-
import pycurl2
import sys


class HTTP:
    def __init__(self,timeout=0,debug=0,
            cookiefile="/noexists",cookiejar=None,
            proxy=None 
            ):
        self.curl=pycurl2.Curl()
        self.curl.setopt(self.curl.TIMEOUT,timeout)
        self.curl.setopt(self.curl.USERAGENT,
                "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/537.36")
        self.curl.setopt(self.curl.ENCODING,
                "gzip,deflate"
                )
        self.curl.setopt(self.curl.VERBOSE,debug)
        self.curl.setopt(self.curl.COOKIEFILE,cookiefile)
        self.curl.setopt(self.curl.FOLLOWLOCATION,1)
        self.curl.setopt(self.curl.MAXREDIRS,5)
        self.curl.setopt(self.curl.AUTOREFERER,1)
        if cookiejar:
            self.curl.setopt(self.curl.COOKIEJAR,cookiejar)
        if proxy:
            self.curl.setopt(self.curl.PROXY,proxy)
        self.curl.setopt(self.curl.SSL_VERIFYPEER,0)
        self.last_url= None

    def get(self,url,output=None):
        self.curl.setopt(self.curl.HTTPGET,1)
        self.curl.setopt(self.curl.URL,url)
        if self.last_url:
            self.curl.setopt(self.curl.REFERER,self.last_url)
        self.last_url = url
        if output:
            if callable(output):
                self.curl.setopt(self.curl.WRITEFUNCTION,output)
            elif hasattr(output,"write") and callable(output.write):
                self.curl.setopt(self.curl.WRITEFUNCTION,output.write)
            elif isinstance(output,str):
                self.curl.setopt(self.curl.WRITEFUNCTION, open(output,"wb").write)
            else:
                raise TypeError("output must be callable or file-object")
        self.curl.perform()
        return self.curl.getinfo(self.curl.RESPONSE_CODE)

class RedirOut:
    def __init__(self, fname):
        self.fp=open(fname,"a")
        self.saved_stdout=sys.stdout
        self.saved_stderr=sys.stderr
        sys.stdout=self
        sys.stderr=self
    def write(self, text):
        self.fp.write(text)
        n=self.saved_stdout.write(text)
        self.fp.flush()
        self.saved_stdout.flush()
        return n
if __name__ == "__main__":
    h=HTTP(timeout=20,debug=1,proxy="socks5://127.0.0.1:8888/",
            cookiefile="cookie.txt",cookiejar="cookie.txt"
            )
    print h.get("http://www.btspread.com/search/aaaa",open("test.txt","w").write)
    print h.get("http://www.btspread.com/search/aaaa/1",open("test.txt","w").write)
